package com.gviiii.pprf.netty.event;


import com.gviiii.pprf.netty.Header;
import com.gviiii.pprf.netty.NettyMessage;
import com.gviiii.pprf.netty.RfNioClient;
import com.gviiii.pprf.utils.JsonUtils;
import com.gviiii.pprf.utils.SpringContextUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * udp 处理器
 */
public class EventChannelHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private static final Logger logger = LoggerFactory.getLogger(EventChannelHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channel active");
        super.channelActive(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        EventEndpoint.chc = ctx;
        super.handlerAdded(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, DatagramPacket datagramPacket) throws Exception {
        EventEndpoint eventEndpoint = SpringContextUtils.getBean("eventEndpoint");
        RfNioClient rfNioClient=SpringContextUtils.getBean("rfNioClient");
        if (datagramPacket != null) {
            ByteBuf byteBuf = datagramPacket.content();
            String decode = byteBuf.toString(CharsetUtil.UTF_8);
            NettyMessage message = (NettyMessage) JsonUtils.readObjectByString(decode, NettyMessage.class);
            //发送 接收连接消息
            if (Header.CONNECTED_MSG.equals(message.getHeader())) {
                message.setHeader(Header.RECEIVE_CONNECTED_MSG);
                InetSocketAddress sender = datagramPacket.sender();
                message.setBody(sender.getHostName()+":"+sender.getPort());
                assert eventEndpoint != null;
                eventEndpoint.send(message);
            }
            //接受 应答消息 重连rf server
            if (Header.REPLY_RECEIVE_CONNECTED_MSG.equals(message.getHeader())){
                assert rfNioClient != null;
                rfNioClient.reconnet();
            }
        }
    }
}
